import { ElMessage } from 'element-plus'

// 离线数据管理
class OfflineManager {
  private db: IDBDatabase | null = null
  private readonly dbName = 'MusicFestivalOffline'
  private readonly version = 1
  private readonly stores = {
    performances: 'performances',
    artists: 'artists',
    facilities: 'facilities',
    userData: 'userData',
    cache: 'cache'
  }

  // 初始化数据库
  async init(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version)

      request.onerror = () => {
        console.error('IndexedDB初始化失败')
        reject(new Error('IndexedDB初始化失败'))
      }

      request.onsuccess = () => {
        this.db = request.result
        console.log('IndexedDB初始化成功')
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result

        // 创建演出数据存储
        if (!db.objectStoreNames.contains(this.stores.performances)) {
          const performanceStore = db.createObjectStore(this.stores.performances, { keyPath: 'id' })
          performanceStore.createIndex('startTime', 'startTime', { unique: false })
          performanceStore.createIndex('artistId', 'artistId', { unique: false })
        }

        // 创建艺人数据存储
        if (!db.objectStoreNames.contains(this.stores.artists)) {
          const artistStore = db.createObjectStore(this.stores.artists, { keyPath: 'id' })
          artistStore.createIndex('name', 'name', { unique: false })
          artistStore.createIndex('musicType', 'musicType', { unique: false })
        }

        // 创建设施数据存储
        if (!db.objectStoreNames.contains(this.stores.facilities)) {
          const facilityStore = db.createObjectStore(this.stores.facilities, { keyPath: 'id' })
          facilityStore.createIndex('name', 'name', { unique: false })
          facilityStore.createIndex('type', 'type', { unique: false })
          facilityStore.createIndex('floor', 'floor', { unique: false })
        }

        // 创建用户数据存储
        if (!db.objectStoreNames.contains(this.stores.userData)) {
          const userStore = db.createObjectStore(this.stores.userData, { keyPath: 'key' })
        }

        // 创建缓存存储
        if (!db.objectStoreNames.contains(this.stores.cache)) {
          const cacheStore = db.createObjectStore(this.stores.cache, { keyPath: 'key' })
          cacheStore.createIndex('timestamp', 'timestamp', { unique: false })
        }
      }
    })
  }

  // 检查网络状态
  isOnline(): boolean {
    return navigator.onLine
  }

  // 监听网络状态变化
  onNetworkChange(callback: (online: boolean) => void): void {
    window.addEventListener('online', () => callback(true))
    window.addEventListener('offline', () => callback(false))
  }

  // 存储演出数据
  async storePerformances(performances: any[]): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.performances], 'readwrite')
    const store = transaction.objectStore(this.stores.performances)

    for (const performance of performances) {
      await this.addToStore(store, performance)
    }
  }

  // 获取演出数据
  async getPerformances(): Promise<any[]> {
    if (!this.db) return []

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.stores.performances], 'readonly')
      const store = transaction.objectStore(this.stores.performances)
      const request = store.getAll()

      request.onsuccess = () => {
        resolve(request.result || [])
      }

      request.onerror = () => {
        reject(new Error('获取演出数据失败'))
      }
    })
  }

  // 存储艺人数据
  async storeArtists(artists: any[]): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.artists], 'readwrite')
    const store = transaction.objectStore(this.stores.artists)

    for (const artist of artists) {
      await this.addToStore(store, artist)
    }
  }

  // 获取艺人数据
  async getArtists(): Promise<any[]> {
    if (!this.db) return []

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.stores.artists], 'readonly')
      const store = transaction.objectStore(this.stores.artists)
      const request = store.getAll()

      request.onsuccess = () => {
        resolve(request.result || [])
      }

      request.onerror = () => {
        reject(new Error('获取艺人数据失败'))
      }
    })
  }

  // 存储设施数据
  async storeFacilities(facilities: any[]): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.facilities], 'readwrite')
    const store = transaction.objectStore(this.stores.facilities)

    for (const facility of facilities) {
      await this.addToStore(store, facility)
    }
  }

  // 获取设施数据
  async getFacilities(): Promise<any[]> {
    if (!this.db) return []

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.stores.facilities], 'readonly')
      const store = transaction.objectStore(this.stores.facilities)
      const request = store.getAll()

      request.onsuccess = () => {
        resolve(request.result || [])
      }

      request.onerror = () => {
        reject(new Error('获取设施数据失败'))
      }
    })
  }

  // 存储用户数据
  async storeUserData(key: string, data: any): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.userData], 'readwrite')
    const store = transaction.objectStore(this.stores.userData)
    
    await this.addToStore(store, { key, data, timestamp: Date.now() })
  }

  // 获取用户数据
  async getUserData(key: string): Promise<any> {
    if (!this.db) return null

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.stores.userData], 'readonly')
      const store = transaction.objectStore(this.stores.userData)
      const request = store.get(key)

      request.onsuccess = () => {
        resolve(request.result?.data || null)
      }

      request.onerror = () => {
        reject(new Error('获取用户数据失败'))
      }
    })
  }

  // 缓存API响应
  async cacheResponse(key: string, data: any, ttl: number = 3600000): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.cache], 'readwrite')
    const store = transaction.objectStore(this.stores.cache)
    
    await this.addToStore(store, {
      key,
      data,
      timestamp: Date.now(),
      ttl
    })
  }

  // 获取缓存的响应
  async getCachedResponse(key: string): Promise<any> {
    if (!this.db) return null

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.stores.cache], 'readonly')
      const store = transaction.objectStore(this.stores.cache)
      const request = store.get(key)

      request.onsuccess = () => {
        const result = request.result
        if (!result) {
          resolve(null)
          return
        }

        // 检查是否过期
        if (Date.now() - result.timestamp > result.ttl) {
          // 删除过期数据
          this.deleteCachedResponse(key)
          resolve(null)
          return
        }

        resolve(result.data)
      }

      request.onerror = () => {
        reject(new Error('获取缓存数据失败'))
      }
    })
  }

  // 删除缓存
  async deleteCachedResponse(key: string): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.cache], 'readwrite')
    const store = transaction.objectStore(this.stores.cache)
    const request = store.delete(key)

    return new Promise((resolve, reject) => {
      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('删除缓存失败'))
    })
  }

  // 清理过期缓存
  async cleanExpiredCache(): Promise<void> {
    if (!this.db) return

    const transaction = this.db.transaction([this.stores.cache], 'readwrite')
    const store = transaction.objectStore(this.stores.cache)
    const index = store.index('timestamp')
    const request = index.openCursor()

    request.onsuccess = () => {
      const cursor = request.result
      if (cursor) {
        const record = cursor.value
        if (Date.now() - record.timestamp > record.ttl) {
          cursor.delete()
        }
        cursor.continue()
      }
    }
  }

  // 添加到存储
  private async addToStore(store: IDBObjectStore, data: any): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = store.put(data)
      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('存储数据失败'))
    })
  }

  // 同步在线数据
  async syncOnlineData(): Promise<void> {
    if (!this.isOnline()) {
      ElMessage.warning('网络连接不可用，无法同步数据')
      return
    }

    try {
      // 这里可以添加数据同步逻辑
      // 例如：将离线时的操作同步到服务器
      ElMessage.success('数据同步完成')
    } catch (error) {
      console.error('数据同步失败:', error)
      ElMessage.error('数据同步失败')
    }
  }

  // 获取存储使用情况
  async getStorageUsage(): Promise<{ used: number; total: number }> {
    if (!navigator.storage || !navigator.storage.estimate) {
      return { used: 0, total: 0 }
    }

    try {
      const estimate = await navigator.storage.estimate()
      return {
        used: estimate.usage || 0,
        total: estimate.quota || 0
      }
    } catch (error) {
      console.error('获取存储使用情况失败:', error)
      return { used: 0, total: 0 }
    }
  }
}

// 创建单例实例
export const offlineManager = new OfflineManager()

// 离线功能工具函数
export const offlineUtils = {
  // 初始化离线功能
  async init() {
    await offlineManager.init()
    
    // 监听网络状态变化
    offlineManager.onNetworkChange((online) => {
      if (online) {
        ElMessage.success('网络连接已恢复')
        // 可以在这里触发数据同步
        offlineManager.syncOnlineData()
      } else {
        ElMessage.warning('网络连接已断开，已切换到离线模式')
      }
    })

    // 定期清理过期缓存
    setInterval(() => {
      offlineManager.cleanExpiredCache()
    }, 300000) // 每5分钟清理一次
  },

  // 检查是否在线
  isOnline() {
    return offlineManager.isOnline()
  },

  // 获取演出数据（优先从缓存获取）
  async getPerformances() {
    if (offlineManager.isOnline()) {
      // 在线时从API获取并缓存
      try {
        // 这里应该调用实际的API
        const performances = await offlineManager.getPerformances()
        await offlineManager.cacheResponse('performances', performances, 1800000) // 30分钟缓存
        return performances
      } catch (error) {
        console.error('获取演出数据失败，使用离线数据:', error)
      }
    }
    
    // 离线时从本地存储获取
    return await offlineManager.getPerformances()
  },

  // 获取艺人数据（优先从缓存获取）
  async getArtists() {
    if (offlineManager.isOnline()) {
      try {
        const artists = await offlineManager.getArtists()
        await offlineManager.cacheResponse('artists', artists, 3600000) // 1小时缓存
        return artists
      } catch (error) {
        console.error('获取艺人数据失败，使用离线数据:', error)
      }
    }
    
    return await offlineManager.getArtists()
  },

  // 获取设施数据（优先从缓存获取）
  async getFacilities() {
    if (offlineManager.isOnline()) {
      try {
        const facilities = await offlineManager.getFacilities()
        await offlineManager.cacheResponse('facilities', facilities, 7200000) // 2小时缓存
        return facilities
      } catch (error) {
        console.error('获取设施数据失败，使用离线数据:', error)
      }
    }
    
    return await offlineManager.getFacilities()
  },

  // 存储用户偏好设置
  async storeUserPreference(key: string, data: any) {
    await offlineManager.storeUserData(key, data)
  },

  // 获取用户偏好设置
  async getUserPreference(key: string) {
    return await offlineManager.getUserData(key)
  },

  // 手动同步数据
  async syncData() {
    await offlineManager.syncOnlineData()
  },

  // 获取存储使用情况
  async getStorageInfo() {
    return await offlineManager.getStorageUsage()
  }
}

export default offlineManager
